// 手机号脱敏显示函数
function maskPhone(phone) {
    if (!phone) return '';
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}

// 获取DOM元素
const profileUsernameSpan = document.getElementById('profileUsername');
const profileGenderSpan = document.getElementById('profileGender');
const profilePhoneSpan = document.getElementById('profilePhone');
const profileAvatarImg = document.getElementById('profileAvatar');
const avatarInput = document.getElementById('avatarInput');
const changePasswordBtn = document.querySelector('.change-password-btn');
const togglePhoneBtn = document.querySelector('.toggle-phone-btn');

// 加载用户信息并显示
/**
 * ajax后端返回的数据(数据名前要加data)
 * userId,
 * userName,
 * password,
 * sex（0-未知，1-男，2-女）,
 * status,
 * phone,
 * avatar,
 * 
 */
async function loadUserProfile() {


    try {
        // 使用 jQuery AJAX 获取用户信息(测试成功，头像地址需要优化)
        $.ajax({
            url: 'http://localhost:8080/user/findUserById',
            type: 'Post',
            dataType: 'json',
            headers: {
                'token': `${localStorage.getItem('token') || ''}`
            },
            data: {
                userId: localStorage.getItem('userId') || ''
            },
            success: function (response) {
                console.log(response.data);
                // 更新用户信息显示
                profileUsernameSpan.textContent = response.data.userName || '未知用户';
                if (response.data.sex === '0') {
                    profileGenderSpan.textContent = '未知';
                } else if (response.data.sex === '1') {
                    profileGenderSpan.textContent = '男';
                } else if (
                    response.data.sex === '2') {
                    profileGenderSpan.textContent = '女';
                }
                profilePhoneSpan.textContent = maskPhone(response.data.phone);
                

                profileAvatarImg.src ="http://localhost:8080"+response.data.avatar;

                // 保存完整用户信息到 localStorage，供手机号切换使用
                localStorage.setItem('userInfo', JSON.stringify(response));
            },
            error: function (xhr, status, error) {
                console.error('加载用户信息失败:', error, xhr.responseText);
                if (xhr.status === 401) {
                    // token过期或无效
                    logout(); // 调用 logout 函数清除存储并跳转
                } else {
                    alert('加载用户信息失败，请稍后重试');
                }
            }
        });

    } catch (error) {
        console.error('加载用户信息请求异常:', error);
        alert('加载用户信息失败，请稍后重试');
    }
}

// 切换手机号显示
// 注意：这里假设在 loadUserProfile 中已经将完整的 userInfo 保存到了 localStorage
function togglePhoneDisplay() {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
    const currentPhoneDisplay = profilePhoneSpan.textContent;
    const toggleBtnIcon = togglePhoneBtn.querySelector('i');

    if (currentPhoneDisplay.includes('*')) {
        // 当前显示脱敏手机号，切换为完整手机号
        profilePhoneSpan.textContent = userInfo.phone || '';
        toggleBtnIcon.className = 'fas fa-eye-slash';
    } else {
        // 当前显示完整手机号，切换为脱敏手机号
        profilePhoneSpan.textContent = maskPhone(userInfo.phone || '');
        toggleBtnIcon.className = 'fas fa-eye';
    }
}

// 处理头像上传(测试成功，返回图片存储地址)
avatarInput.addEventListener('change', async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    const formData = new FormData();
    formData.append('file', file);
    formData.append('userId', localStorage.getItem('userId') || '');

    try {
        // 使用 jQuery AJAX 进行头像上传
        $.ajax({
            url: 'http://localhost:8080/user/addAvatar  ',
            type: 'POST',
            data: formData,
            processData: false, // Important for FormData
            contentType: false, // Important for FormData
            headers: {
                'token': `${localStorage.getItem('token') || ''}`
            },
            success: function (response) {
                if (response.code === 200) {

                    profileAvatarImg.src = "http://localhost:8080"+response.data;
                    // 更新本地存储的用户信息
                    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                    userInfo.avatar = response.avatarUrl;
                    localStorage.setItem('userInfo', JSON.stringify(userInfo));
                    alert('头像上传成功！');
                } else {
                    alert(response.message || '上传头像失败，请稍后重试');
                }

            },
            error: function (xhr, status, error) {
                console.error('上传头像失败:', xhr.responseText);
                if (xhr.status === 401) {
                    logout();
                } else {
                    try {
                        const errorResponse = JSON.parse(xhr.responseText);
                        alert(errorResponse.message || '上传头像失败，请稍后重试');
                    } catch (e) {
                        alert('上传头像失败，请稍后重试');
                    }
                }
            }
        });

    } catch (error) {
        console.error('上传头像请求异常:', error);
        alert('上传头像失败，请稍后重试');
    }
});

// 修改密码按钮点击事件
changePasswordBtn.addEventListener('click', async () => {
    const oldPassword = prompt('请输入原密码：');
    if (!oldPassword) return;

    const newPassword = prompt('请输入新密码：');
    if (!newPassword) return;

    const confirmPassword = prompt('请确认新密码：');
    if (!confirmPassword) return;

    if (newPassword !== confirmPassword) {
        alert('两次输入的密码不一致');
        return;
    }

    if (newPassword.length < 6) {
        alert('密码长度至少为6位');
        return;
    }

    try {
        // 使用 jQuery AJAX 进行修改密码请求
        $.ajax({
            url: '/api/user/password',
            type: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify({
                oldPassword: oldPassword,
                newPassword: newPassword
            }),
            headers: {
                'Authorization': `Bearer ${token}`
            },
            success: function (response) {
                alert('密码修改成功，请重新登录');
                logout(); // 密码修改后强制重新登录
            },
            error: function (xhr, status, error) {
                console.error('修改密码失败:', xhr.responseText);
                if (xhr.status === 401) {
                    logout();
                } else {
                    try {
                        const errorResponse = JSON.parse(xhr.responseText);
                        alert(errorResponse.message || '修改密码失败');
                    } catch (e) {
                        alert('修改密码失败，请稍后重试');
                    }
                }
            }
        });

    } catch (error) {
        console.error('修改密码请求异常:', error);
        alert('修改密码失败，请稍后重试');
    }
});

// 退出登录 (Utility function)
function logout() {
    localStorage.removeItem('token');
    localStorage.removeItem('userPhone');
    localStorage.removeItem('userInfo');
    window.location.href = '/login.html';
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    loadUserProfile();
    if (togglePhoneBtn) {
        togglePhoneBtn.addEventListener('click', togglePhoneDisplay);
    }
    if (changePasswordBtn) {
        changePasswordBtn.addEventListener('click', changePasswordBtn);
    }
}); 